package com.laicunba.ext.web.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.laicunba.util.CacheUtil;
import com.laicunba.util.SessionUtil;
import com.laicunba.util.StringUtil;

@Component
public class ConsolePermissionFilter implements HandlerInterceptor {
	private static final Logger LOG = Logger.getLogger(ConsolePermissionFilter.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println(request.getContextPath() + "Permission ->" + request.getRequestURI());

		if ("root".equalsIgnoreCase(SessionUtil.CURRENT_USER_ID.get())) {
			return true;
		}
		String uri = request.getRequestURI();
		if (StringUtil.isNotEmpty(request.getContextPath())) {
			uri = uri.substring(request.getContextPath().length());

		}
		if ("1".equalsIgnoreCase(CacheUtil.hget("manager.permission." + SessionUtil.CURRENT_USER_ID.get(), uri))) {
			return true;
		}
		LOG.warn(String.format("usr:%s,403:%s", SessionUtil.CURRENT_USER_ID.get(), uri));
		response.setStatus(403);
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub

	}

}
